package com.we.wecc.bg.mid.impl;

import com.we.wecc.aw.db.mapper.*;
import com.we.wecc.aw.db.model.*;
import com.we.wecc.aw.mid.model.in.AwardIn;
import com.we.wecc.aw.mid.model.out.FriendsBoostOut;
import com.we.wecc.bg.mid.model.out.AwardJoinLogOut;
import com.we.wecc.bg.mid.model.in.AwardProductIn;
import com.we.wecc.bg.mid.model.out.ParticipationCountOut;
import com.we.wecc.bg.mid.model.out.WinOut;
import com.we.wecc.bg.mid.service.BackAwardService;
import com.we.wecc.us.db.mapper.UserMapper;
import com.we.wecc.us.db.model.ActUser;
import com.we.wecc.us.db.model.User;
import com.we.wecc.us.mid.service.ActUserService;
import com.x.share.db.model.Pagination;
import com.x.share.mid.exception.HelperException;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.x.share.mid.utils.DateUtils.IncDate;

@Service
public class BackAwardServiceImpl implements BackAwardService {

    @Resource
    AwardProductMapper awardProductMapper;

    @Resource
    AwardMapper awardMapper;

    @Resource
    AwardInvestLogMapper awardInvestLogMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    ActUserService actUserService;

    @Resource
    FriendsBoostMapper friendsBoostMapper;

    @Resource
    AwardWinMapper awardWinMapper;


    @Override
    public AwardProduct saveAwardProduct(AwardProductIn in) {
        AwardProduct ap = in.toAwardProduct();
        ap.setCreateTime(new Date());
        if (ap.getId() != null && ap.getId() > 0) {
            AwardProduct awardProduct = awardProductMapper.selectByPrimaryKey(ap.getId());
            if (awardProduct == null) {
                throw new HelperException("该奖品不存在！");
            }
            awardProductMapper.updateByPrimaryKeySelective(ap);
        } else {
            awardProductMapper.insertSelective(ap);
        }
        return ap;
    }

    @Override
    public Pagination<AwardProduct> getAwardProductList(Integer pageNo, Integer pageSize) {
        AwardProductExample ex = new AwardProductExample();
        ex.setOrderByClause("createTime desc");
        RowBounds rb = new RowBounds(Pagination.offset(pageNo, pageSize), Pagination.limit(pageSize));
        List<AwardProduct> list = awardProductMapper.selectByExampleWithRowbounds(ex, rb);
        int count = (int) awardProductMapper.countByExample(ex);
        Pagination<AwardProduct> page = new Pagination<>(pageNo, pageSize);
        page.setItems(list);
        page.setRecords(count);
        return page;
    }

    @Override
    public Award saveAward(AwardIn in) {
        Award a = in.toAward();
        a.setCreateTime(new Date());
        a.setDelFlag(0);
        a.setAwardStatus(0);
        if (in.getId() != null) {
            awardMapper.updateByPrimaryKeySelective(a);
        } else {
            awardMapper.insert(a);
        }
        return a;
    }

    @Override
    public Pagination<AwardJoinLogOut> getJoinLog(int awardId, int pageNo, int pageSize) {
        List<AwardJoinLogOut> item = new ArrayList<>();
        AwardJoinLogOut out = new AwardJoinLogOut();
        AwardInvestLogExample ex = new AwardInvestLogExample();
        ex.or().andAwardIdEqualTo(awardId);
        List<AwardInvestLog> list = awardInvestLogMapper.selectByExample(ex);
        if (list.isEmpty()) {
            throw new HelperException("活动id有误！");
        }
        Map<Long, List<AwardInvestLog>> collect = list.stream().collect(Collectors.groupingBy(AwardInvestLog::getUserId));
        collect.forEach((k, v) -> {
            User user = userMapper.selectByPrimaryKey(k);
            out.setUserId(k);
            out.setImg(user.getHeadimage());
            out.setTel(user.getTel());
            ActUser actUser = actUserService.getActUser(k);
            out.setInvestRemainTimes(actUser.getInvestRemainTimes() + actUser.getInvestTimes());
            out.setAlreadyInvestTimes(v.size());
            out.setAmount(v.get(0).getNum());
            out.setAlreadyInvestNum(v.size() * v.get(0).getNum());
            FriendsBoostExample fex = new FriendsBoostExample();
            fex.or().andFriendsIdEqualTo(k).andAwardIdEqualTo(awardId);
            int count = (int) friendsBoostMapper.countByExample(fex);
            out.setBoostTimes(count);
            fex.clear();
            fex.or().andUserIdEqualTo(k);
            int inviteTimes = (int) friendsBoostMapper.countByExample(fex);
            out.setInviteTimes(inviteTimes);
            //todo 权重
            item.add(out);
        });
        return new Pagination<>(item, item.size(), pageNo, pageSize);
    }

    @Override
    public ParticipationCountOut getParticipation(int awardId) {
        ParticipationCountOut out = new ParticipationCountOut();
        AwardInvestLogExample ex = new AwardInvestLogExample();
        ex.or().andAwardIdEqualTo(awardId);
        List<AwardInvestLog> list = awardInvestLogMapper.selectByExample(ex);
        int participationNum = (int) list.stream().map(AwardInvestLog::getUserId).distinct().count();
        out.setParticipationNum(participationNum);
        int joinTimes = (int) awardInvestLogMapper.countByExample(ex);
        out.setJoinTimes(joinTimes);
        int newCustomer = 0;
        for (AwardInvestLog s : list) {
            ex.clear();
            ex.or().andAwardIdNotEqualTo(awardId).andUserIdNotEqualTo(s.getUserId());
            List<AwardInvestLog> log = awardInvestLogMapper.selectByExample(ex);
            if (log.isEmpty()) {
                newCustomer++;
            }
        }
        int oldCustomer = participationNum - newCustomer;
        out.setOldCustomer(oldCustomer);
        out.setNewCustomer(newCustomer);
        Award a = awardMapper.selectByPrimaryKey(awardId);
        out.setInvestment(a.getInvestment());
        out.setTimes(a.getTimes());
        return out;
    }

    @Override
    public WinOut getCurrWinner(int awardId) {
        AwardWinExample ex = new AwardWinExample();
        ex.or().andAwardIdEqualTo(awardId);
        List<AwardWin> list = awardWinMapper.selectByExample(ex);
        if(list.isEmpty()){
            throw new HelperException("暂未开奖！");
        }
        AwardWin win = list.get(0);
        WinOut.UserInfo ui= WinOut.UserInfo.from(userMapper.selectByPrimaryKey(win.getUserId()));
        return WinOut.from(win,ui);
    }
}
